<template>

  <div class="app-container">
    <!-- 搜索 -->
    <div class="filter-container">
      <el-select clearable v-model="getListData.role_id" placeholder="请选择角色" size="medium" class="filter-item"
        @change="bindRoleIdChange">
        <el-option :label="v.name" v-for="(v,k) in roles" :key="k" :value="v.id">
        </el-option>
      </el-select>
      <el-input size="medium" v-model="getListData.usercode" placeholder="请输入账号" style="width: 200px;margin-left:10px;"
        class="filter-item" clearable />
      <el-button size="medium" class="filter-item" type="primary" icon="el-icon-search" @click="getAdminList">搜索
      </el-button>
      <el-button size="medium" class="filter-item" type="primary" @click="handleCreate">新增账户
      </el-button>
      <el-button size="medium" class="filter-item" type="success" @click="showDiaLog">批量设置账户角色
      </el-button>
      <el-button size="medium" v-loading.fullscreen.lock="downloadLoading" class="filter-item" type="warning" @click="export2Excel">导出EXCEL</el-button>

    </div>

    <!-- 表格 -->
    <el-table :key="tableKey" ref="itsmDataTable" v-loading="listLoading" :data="tableData" highlight-current-row
      border>
      <el-table-column type="selection" width="40"></el-table-column>
      <el-table-column prop="usercode" label="账号" width="180" sortable></el-table-column>
      <el-table-column prop="username" label="用户名" width="180"></el-table-column>
      <el-table-column prop="role_name" label="角色"></el-table-column>
      <el-table-column prop="valid_char" label="账户状态"></el-table-column>
      <el-table-column label="操作" fixed="right">
        <template slot-scope="{row}">
          <el-button size="mini" type="primary" @click="handleEdit(row)">编辑</el-button>
          <el-popconfirm confirm-button-text='确认' cancel-button-text='取消' title='确认修改当前状态' @onConfirm="doValid(row.uuid)" style="margin-left:10px;">
            <el-button size="mini" :type="row.valid=='1'?'danger':'success'" slot="reference">
              {{row.valid=='1'?'禁用':'启用'}}</el-button>
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <!-- 分页 -->
    <pagination v-show="totalPage>0" :total="totalPage" :page.sync="getListData.pageNo"
      :limit.sync="getListData.pageSize" @pagination="getAdminList" />

    <!-- 编辑，新增弹窗 -->
    <el-dialog :title="textMap[dialogStatus]+'账户'" :visible.sync="dialogVisible" width="30%"
      :close-on-click-modal='false'>
      <el-form :model="form" ref='accountForm'>
        <el-input v-model="form.uuid" class="hide"></el-input>
        <el-form-item label="账号" :rules="[{ required: true, message: '账号不能为空'}]" prop="usercode">
          <el-input placeholder="请输入账号" clearable v-model="form.usercode"></el-input>
        </el-form-item>
        <el-form-item label="用户名" :rules="[{ required: true, message: '用户名不能为空'}]" prop="username">
          <el-input placeholder="请输入用户名" clearable v-model="form.username"></el-input>
        </el-form-item>
        <el-form-item label="角色" prop="role_id" :rules="[{ type: 'array',required: true, message: '请选择至少一个角色'}]">
          <el-checkbox-group v-model="form.role_id" class="role-checkbox">
            <el-checkbox :label="v.id" v-for="(v,k) in roles" :key="k">{{v.name}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogStatus==='create'?updateData(''):updateData()">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 批量设置弹窗 -->
    <el-dialog title="批量设置账户角色" :visible.sync="dialogVisible1" width="30%" :close-on-click-modal="false">
      <el-form :model="form1" ref='rolesForm'>
        <el-form-item label="角色" prop="role_id" :rules="[{ required: true, message: '请选择角色'}]">
          <el-radio-group v-model="form1.role_id" class="role-radio">
            <el-radio :label="v.id" v-for="(v,k) in roles" :key="k">{{v.name}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="账户" prop="adminList" :rules="[{ type: 'array',required: true, message: '请选择至少一个账户'}]">
          <el-select v-model="form1.adminList" clearable filterable multiple placeholder="请选择" style="width:50%;">
            <el-option v-for="(v,k) in accountList" :key="k" :label="v.usercode" :value="v.id">
            </el-option>
          </el-select>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible1 = false">取 消</el-button>
        <el-button type="primary" @click="setRole('add')">批量添加</el-button>
        <el-button type="danger" @click="setRole('delete')">批量删除</el-button>
      </span>
    </el-dialog>

  </div>

</template>


<script>
  import {
    Message
  } from 'element-ui'
  import {
    getAdminAccountList,
    getAccountInfo,
    saveAdminInfo,
    changeAccountVaild,
    getAdminAccountExport,
    getRoles,
    setBatchRole
  } from '@/app/api/admin'
  import Pagination from '@/app/components/Pagination' // secondary package based on el-pagination
  export default {
    components: {
      Pagination
    },
    name: 'AdminIndex',
    data() {
      return {
        // 列表
        tableKey: 0,
        tableData: [],
        totalPage: 1,
        listLoading: true,
        getListData: {
          pageNo: 1,
          pageSize: 10,
          usercode: '',
          username: '',
          role_id: ''
        },

        // 编辑，新增弹窗
        dialogVisible: false,
        form: {
          uuid: '',
          usercode: '',
          username: '',
          role_id: []
        },
        roles: [], //角色列表
        dialogStatus: '', //编辑或新增
        textMap: {
          update: '编辑',
          create: '新增'
        },

        // 批量设置账户角色
        dialogVisible1: false,
        form1: {
          role_id: '',
          adminList: [],
          action: ''
        },
        accountList: [], //账户列表

        // 导出
        downloadLoading: false,

      }
    },
    created() {
      this.getAdminList()
      this.getRoleList()
    },
    methods: {
      // 获取账户列表
      getAdminList() {
        this.listLoading = true
        getAdminAccountList(this.getListData)
          .then((res) => {
            // console.log('res', res);
            this.tableData = res.data.ret
            this.totalPage = res.data.count
            this.listLoading = false
          }).catch((error) => {
            console.log('getAdminAccountList error', error)
          })
      },
      // 获取角色列表
      getRoleList() {
        getRoles(this.getListData)
          .then((res) => {
            this.roles = res.data
            // console.log('this.roles', this.roles);
          }).catch((error) => {
            console.log('getRoles error', error)
          })
      },

      // 编辑
      handleEdit(row) {
        this.form = Object.assign({}, row) // copy obj
        this.form.role_id = this.form.role_id.split(",");
        this.dialogStatus = 'update'
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs['accountForm'].clearValidate()
        })
      },
      // 重置form
      resetForm() {
        this.form = {
          uuid: '',
          usercode: '',
          username: '',
          role_id: []
        }
      },
      // 新增，编辑保存
      updateData(id) {
        this.$refs['accountForm'].validate((valid) => {
          if (valid) {
            if (id) {
              this.form.id = id
            }
            saveAdminInfo(this.form)
              .then((res) => {
                if (res.code == '00000') {
                  Message({
                    message: '保存成功',
                    type: 'success',
                    duration: 5 * 1000
                  })
                  this.getAdminList();
                }
              }).catch((error) => {
                console.log('saveAdminInfo error', error)
              })
            this.dialogVisible = false
          } else {
            return false;
          }
        })

      },
      // 启用/禁用
      doValid(uuid) {
        changeAccountVaild({
            uuid
          })
          .then((res) => {
            if (res.code == '00000') {
              Message({
                message: '操作成功',
                type: 'success',
                duration: 5 * 1000
              })
              this.getAdminList();
            }
          }).catch((error) => {
            console.log('changeAccountVaild error', error)
          })
      },

      // 头部按钮等
      // 新增保存
      handleCreate() {
        this.resetForm()
        this.dialogStatus = 'create'
        this.dialogVisible = true
        this.$nextTick(() => {
          this.$refs['accountForm'].clearValidate()
        })
      },

      // 导出
      export2Excel() {
        this.downloadLoading = true
        require.ensure([], () => {
          const {
            export_json_to_excel,
          } = require("../../components/vendor/Export2Excel");
          const tHeader = ["账户", "用户名", "角色"];
          const filterVal = ["usercode", "username", "role_name"];
          getAdminAccountExport({})
            .then((res) => {
              const list = res.data;
              const data = this.formatJson(filterVal, list);
              export_json_to_excel(tHeader, data, "账户列表");
              this.downloadLoading = false
            }).catch((error) => {
              console.log('getAdminAccountExport error', error)
            })
        });
      },
      formatJson(filterVal, jsonData) {
        return jsonData.map((v) => filterVal.map((j) => v[j]));
      },


      // 设置账户角色
      showDiaLog() {
        this.resetRolesForm()
        let _selectData = this.$refs.itsmDataTable.selection
        if (!_selectData.length) {
          Message({
            message: '请选择数据',
            type: 'warning',
            duration: 2 * 1000
          })
          return;
        }
        this.form1.adminList = _selectData.map((obj, index) => {
          return obj.id;
        })
        this.accountList = _selectData
        this.dialogVisible1 = true
        this.$nextTick(() => {
          this.$refs['rolesForm'].clearValidate()
        })
      },
      resetRolesForm() {
        this.form1 = {
          role_id: '',
          adminList: []
        }
      },
      // 设置角色
      setRole(action) {
        this.$refs['rolesForm'].validate((valid) => {
          if (valid) {
            this.form1.action = action
            setBatchRole(this.form1)
              .then((res) => {
                // console.log('setBatchRole success', res)
                if (res.code == '00000') {
                  Message({
                    message: '保存成功',
                    type: 'success',
                    duration: 5 * 1000
                  })
                  this.getAdminList();
                }
              }).catch((error) => {
                console.log('setBatchRole error', error)
              })
            this.dialogVisible1 = false
          } else {
            return false;
          }
        })
      },
      // 筛选角色
      bindRoleIdChange() {
        this.getAdminList()
      },

    }
  };

</script>

<style lang="scss">
  .el-form-item__content {
    line-height: 20px;
  }

  .role-checkbox.el-checkbox-group {
    width: 100%;
    display: inline-block;

    .el-checkbox {
      line-height: 0;
    }
  }

  .role-radio.el-radio-group {
    line-height: 20px;
  }

</style>
